package it.unipi.di.rasip.gui;

import it.unipi.di.rasip.Rasip;
import it.unipi.di.rasip.gui.chat.ChatCreator;
import it.unipi.di.rasip.protocol.SipServer;
import it.unipi.di.rasip.utils.IconsFactory;

import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Font;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;

public class WelcomeCanvas extends RASDisplayable implements CommandListener {
	//Singleton
	private static WelcomeCanvas _instance;
	
	public static WelcomeCanvas getInstance() {
		if (null == _instance) {
			_instance = new WelcomeCanvas();
		}
		return _instance;
	}
	
	Image img;
	Command newChatCmd;
	Command exitCmd;
	
	private WelcomeCanvas() {		
		img = IconsFactory.createIcon(IconsFactory.LOGO);

		displayable = new Canvas() {

			protected void paint(Graphics g) {
				int width = getWidth();
			    int height = getHeight();
			    
			    g.setColor(255, 255, 255);
			    g.fillRect(0, 0, width, height);
			    g.setColor(255, 0, 0);
			    Font f = Font.getFont(Font.FACE_SYSTEM, Font.STYLE_BOLD, Font.SIZE_LARGE);
			    g.setFont(f);
				g.drawImage (img, width / 2, height / 2, 
				        Graphics.HCENTER | Graphics.VCENTER);
				g.drawString("Welcome to Rasip", width / 2, height / 2 + 80, Graphics.BASELINE|Graphics.HCENTER);
			}
			
		};
		
		newChatCmd = new Command("New chat", Command.ITEM, 1);
		displayable.addCommand(newChatCmd);

		exitCmd = new Command("Exit", Command.EXIT, 1);
		displayable.addCommand(exitCmd);
		
		displayable.setCommandListener(this);
		SipServer.getInstance().start();
	}

	public void commandAction(Command cmd, Displayable d) {
		if(cmd == newChatCmd) {
			//Start new chat
			ChatCreator cc = ChatCreator.getInstance();
			cc.show();
			//SipServer.getInstance().start();
			new Thread() {
				public void run() {
					//SipServer.getInstance().start();
					super.run();
				}
			}.start();
			
		} else if (cmd == exitCmd) {
			Rasip.getInstance().notifyDestroyed();
		}
	}
}
